<template>
    <div class="layout-container">
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <h2>房屋租赁系统</h2>
        </div>
        <div class="header-right">
          <span>欢迎您，{{ username }}</span>
        </div>
      </el-header>
  
      <el-container class="main-container">
        <!-- 左侧导航栏 -->
        <el-aside width="250px" class="aside">
          <!-- 用户信息卡片 -->
          <div class="user-info">
            <el-avatar :size="64" :src="userAvatar">
              <img src="/src/assets/default-avatar.png"/>
            </el-avatar>
            <h3>{{ username }}</h3>
            <el-button type="primary" size="small" @click="goToProfile">修改个人信息</el-button>
            <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
          </div>
  
          <el-menu
            default-active="2-6"
            class="menu"
            background-color="#304156"
            text-color="#fff"
            active-text-color="#409EFF"
            @select="handleMenuSelect"
          >
            <el-sub-menu index="1">
              <template #title>
                <el-icon><User /></el-icon>
                <span>我是租客</span>
              </template>
              <el-menu-item index="1-1">我的收藏</el-menu-item>
              <el-menu-item index="1-2">消息列表</el-menu-item>
              <el-menu-item index="1-3">我的预约</el-menu-item>
              <el-menu-item index="1-4">我的订单</el-menu-item>
              <el-menu-item index="1-5">我的租房</el-menu-item>
            </el-sub-menu>
  
            <el-sub-menu index="2">
              <template #title>
                <el-icon><House /></el-icon>
                <span>我是房东</span>
              </template>
              <el-menu-item index="2-1">我要出租</el-menu-item>
              <el-menu-item index="2-2">消息列表</el-menu-item>
              <el-menu-item index="2-3">管理出租</el-menu-item>
              <el-menu-item index="2-4">预约反馈</el-menu-item>
              <el-menu-item index="2-5">维修反馈</el-menu-item>
              <el-menu-item index="2-6">租金收入</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
  
        <!-- 主要内容区域 -->
        <el-main class="main">
          <div class="rental-income">
            <!-- 收入概览卡片 -->
            <el-card class="overview-card">
              <template #header>
                <div class="card-header">
                  <span>租金收入概览</span>
                  <el-button type="primary" size="small" @click="fetchIncomeOverview">刷新数据</el-button>
                </div>
              </template>
              
              <div class="overview-content" v-loading="overviewLoading">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="stat-item">
                      <div class="stat-title">总收入</div>
                      <div class="stat-value">¥ {{ formatCurrency(incomeOverview.total_income) }}</div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="stat-item">
                      <div class="stat-title">租赁订单数</div>
                      <div class="stat-value">{{ incomeOverview.total_rents }}</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
            
            <!-- 收入详情卡片 -->
            <el-card class="details-card">
              <template #header>
                <div class="card-header">
                  <span>收入详情</span>
                  <el-button type="primary" size="small" @click="fetchIncomeDetails">刷新数据</el-button>
                </div>
              </template>
              
              <!-- 收入详情表格 -->
              <el-table
                :data="incomeDetails"
                style="width: 100%"
                border
                stripe
                v-loading="detailsLoading"
              >
                <el-table-column prop="house_id" label="房屋ID" width="80" />
                <el-table-column prop="house_address" label="房屋地址" min-width="200" show-overflow-tooltip />
                <el-table-column prop="monthly_rent" label="月租金" width="120">
                  <template #default="scope">
                    ¥ {{ formatCurrency(scope.row.monthly_rent) }}
                  </template>
                </el-table-column>
                <el-table-column prop="tenant_name" label="租户" width="120">
                  <template #default="scope">
                    {{ scope.row.tenant_name || '暂无租户' }}
                  </template>
                </el-table-column>
                <el-table-column prop="start_date" label="租期开始" width="120">
                  <template #default="scope">
                    {{ scope.row.start_date || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="end_date" label="租期结束" width="120">
                  <template #default="scope">
                    {{ scope.row.end_date || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="租金总额" width="120">
                  <template #default="scope">
                    ¥ {{ formatCurrency(scope.row.amount) }}
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  :current-page="currentPage"
                  :page-size="pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </div>
        </el-main>
      </el-container>
  
      <!-- 个人信息修改弹窗 -->
      <el-dialog
        v-model="showProfileDialog"
        title="修改个人信息"
        width="500px"
        @close="handleClose"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <!-- 当前密码验证 -->
          <el-form-item label="当前密码" prop="old_password">
            <el-input v-model="form.old_password" type="password" show-password></el-input>
          </el-form-item>
  
          <!-- 选择要修改的信息类型 -->
          <el-form-item label="修改项目">
            <el-select v-model="editType" placeholder="请选择要修改的信息">
              <el-option label="账户名" value="account_name"></el-option>
              <el-option label="账号" value="username"></el-option>
              <el-option label="密码" value="password"></el-option>
            </el-select>
          </el-form-item>
  
          <!-- 根据选择显示对应的输入框 -->
          <template v-if="editType === 'username'">
            <el-form-item label="新账号" prop="username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
          </template>
  
          <template v-if="editType === 'account_name'">
            <el-form-item label="新账户名" prop="account_name">
              <el-input v-model="form.account_name"></el-input>
            </el-form-item>
          </template>
  
          <template v-if="editType === 'password'">
            <el-form-item label="新密码" prop="password">
              <el-input v-model="form.password" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirm_password">
              <el-input v-model="form.confirm_password" type="password" show-password></el-input>
            </el-form-item>
          </template>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { User, House } from '@element-plus/icons-vue'
  import { useRouter } from 'vue-router'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import axios from 'axios'
  
  const router = useRouter()
  // 从localStorage获取用户名
  const username = ref('')
  const userAvatar = ref('')
  const showProfileDialog = ref(false)
  const editType = ref('')
  const formRef = ref(null)
  
  // 表单数据
  const form = ref({
    old_password: '',
    username: '',
    account_name: '',
    password: '',
    confirm_password: ''
  })
  
  // 验证两次密码是否一致
  const validatePass = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请再次输入密码'))
    } else if (value !== form.value.password) {
      callback(new Error('两次输入密码不一致'))
    } else {
      callback()
    }
  }
  
  // 表单验证规则
  const rules = {
    old_password: [
      { required: true, message: '请输入当前密码', trigger: 'blur' }
    ],
    username: [
      { required: true, message: '请输入新用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    account_name: [
      { required: true, message: '请输入新账户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    confirm_password: [
      { required: true, validator: validatePass, trigger: 'blur' }
    ]
  }
  
  // 租金收入相关数据
  const overviewLoading = ref(false)
  const detailsLoading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const incomeOverview = ref({
    total_income: 0,
    total_rents: 0
  })
  const incomeDetails = ref([])
  
  // 格式化货币
  const formatCurrency = (value) => {
    if (!value && value !== 0) return '-'
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  
  // 获取收入概览
  const fetchIncomeOverview = async () => {
    overviewLoading.value = true
    try {
      const response = await axios.get('http://127.0.0.1:5000/api/landlord/income/overview', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.status === 200) {
        incomeOverview.value = {
          total_income: response.data.data.total_income,
          total_rents: response.data.data.total_rents
        }
      } else {
        ElMessage.error(response.data.msg || '获取收入概览失败')
      }
    } catch (error) {
      console.error('获取收入概览失败:', error)
      ElMessage.error('获取收入概览失败，请稍后重试')
    } finally {
      overviewLoading.value = false
    }
  }
  
  // 获取收入详情
  const fetchIncomeDetails = async () => {
    detailsLoading.value = true
    try {
      const response = await axios.get('http://127.0.0.1:5000/api/landlord/income/details', {
        params: {
          page: currentPage.value,
          per_page: pageSize.value
        },
        headers: {
          'Authorization': `${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.status === 200) {
        incomeDetails.value = response.data.data.income_details
        total.value = response.data.data.total
      } else {
        ElMessage.error(response.data.msg || '获取收入详情失败')
      }
    } catch (error) {
      console.error('获取收入详情失败:', error)
      ElMessage.error('获取收入详情失败，请稍后重试')
    } finally {
      detailsLoading.value = false
    }
  }
  
  // 处理页码变化
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchIncomeDetails()
  }
  
  // 处理每页显示数量变化
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchIncomeDetails()
  }
  
  onMounted(() => {
    // 获取登录时存储的用户信息
    const userId = localStorage.getItem('userId')
    username.value = localStorage.getItem('username') || '用户'
    userAvatar.value = localStorage.getItem('userAvatar') || ''
    
    fetchIncomeOverview()
    fetchIncomeDetails()
  })
  
  // 打开个人信息修改弹窗
  const goToProfile = () => {
    showProfileDialog.value = true
    editType.value = ''
    form.value = {
      old_password: '',
      username: '',
      account_name: '',
      password: '',
      confirm_password: ''
    }
  }
  
  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const data = {
            old_password: form.value.old_password
          }
          
          // 根据选择的修改类型添加相应的数据
          if (editType.value === 'username') {
            data.username = form.value.username
          } else if (editType.value === 'account_name') {
            data.account_name = form.value.account_name
          } else if (editType.value === 'password') {
            data.password = form.value.password
          }
  
          const response = await axios.post('http://127.0.0.1:5000/api/users/updateUserInfo', data, {
            headers: {
              'Authorization': `${localStorage.getItem('token')}`
            }
          })
  
          if (response.data.status === 200) {
            ElMessage.success(response.data.msg)
            // 更新本地存储的用户信息
            if (editType.value === 'username') {
              localStorage.setItem('username', form.value.username)
              username.value = form.value.username
            } else if (editType.value === 'account_name') {
              localStorage.setItem('account_name', form.value.account_name)
              localStorage.setItem('username', form.value.account_name)
              username.value = form.value.account_name
            }
            handleClose()
          } else {
            ElMessage.error(response.data.msg || '修改失败')
          }
        } catch (error) {
          console.error('修改失败:', error)
          ElMessage.error(error.response?.data?.msg || '修改失败，请稍后重试')
        }
      }
    })
  }
  
  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }
  
  // 关闭弹窗
  const handleClose = () => {
    showProfileDialog.value = false
    resetForm()
  }
  
  // 处理退出登录
  const handleLogout = () => {
    ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      // 清除本地存储的信息
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('isAdmin')
      localStorage.removeItem('username')
      localStorage.removeItem('userAvatar')
      
      ElMessage.success('已成功退出登录')
      router.push('/login')
    }).catch(() => {
      // 取消退出登录
    })
  }
  
  const continueBrowsing = () => {
    router.push('/house')
  }
  
  // 菜单处理
  const handleMenuSelect = (index) => {
    switch(index) {
      // 房东相关菜单
      case '2-4': // 预约反馈
        router.push('/landlord/appointment');
        break;
      case '2-5': // 维修反馈
        router.push('/landlord/maintenance');
        break;
      case '2-6': // 租金收入
        router.push('/landlord/income');
        break;
      // 其他菜单项的处理...
      default:
        // 默认处理
        break;
    }
  }
  </script>
  
  <style scoped>
  .layout-container {
    height: 100vh;
    background-color: #f0f2f5;
  }
  
  .header {
    background-color: #409EFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
  }
  
  .header-left h2 {
    color: #fff;
    margin: 0;
  }
  
  .header-right span {
    color: #fff;
  }
  
  .main-container {
    height: calc(100vh - 60px);
  }
  
  .aside {
    background-color: #304156;
    height: 100%;
  }
  
  .menu {
    border-right: none;
  }
  
  .user-info {
    padding: 20px;
    text-align: center;
    background-color: #263445;
    color: #fff;
  }
  
  .user-info h3 {
    margin: 10px 0;
    font-size: 16px;
    color: #fff;
  }
  
  .user-info .el-button {
    margin-top: 10px;
  }
  
  .main {
    padding: 20px;
    background-color: #f0f2f5;
    overflow-y: auto;
  }
  
  .rental-income {
    width: 100%;
  }
  
  .overview-card {
    margin-bottom: 20px;
  }
  
  .details-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .overview-content {
    padding: 20px 0;
  }
  
  .stat-item {
    text-align: center;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 4px;
  }
  
  .stat-title {
    font-size: 16px;
    color: #606266;
    margin-bottom: 10px;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>